package com.yc.sole.erp.baiduOcr;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.json.JSONObject;
import com.yc.sole.framework.exception.BaseException;
import lombok.RequiredArgsConstructor;
import okhttp3.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author yizuomin
 * @date 2024/3/21 12:59
 **/
@Service
@RequiredArgsConstructor
public class OcrService {

    private final BaiduApiConfig apiConfig;
    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    private static final String TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
    private static final String API_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/table";


    /**
     * ocr识别
     *
     * @return
     * @throws IOException
     */
    public String doOcr(MultipartFile file) {
        try {
            String imgStr = Base64Encoder.encode(file.getBytes());
            String imgParam = URLEncoder.encode(imgStr, StandardCharsets.UTF_8);
            String param = "image=" + imgParam;
            return HttpUtil.post(API_URL, getAccessToken(), param);
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + apiConfig.getApiKey()
                + "&client_secret=" + apiConfig.getSecretKey());
        Request request = new Request.Builder()
                .url(TOKEN_URL)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).get("access_token", String.class);
    }
}
